import axios from 'axios';

const API_BASE_URL = 'http://localhost:8080';

const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  withCredentials: true
});

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data;
  },
  error => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      window.location.href = '/';
    }
    return Promise.reject(error);
  }
);

// API 方法
export const childEnglishApi = {
  // 获取应用信息
  async getAppInfo() {
    const response = await api.get('/');
    return response;
  },

  // 用户登录
  async login(credentials) {
    const response = await api.post('/login', credentials);
    return response;
  },

  // 获取用户信息
  async getUserInfo() {
    const response = await api.get('/user/info');
    return response;
  },

  // 获取听力学习数据
  async getListeningData() {
    const response = await api.get('/learning/listening');
    return response;
  },

  // 获取游戏关卡
  async getGameLevels() {
    const response = await api.get('/learning/game/levels');
    return response;
  },

  // 获取孩子学习进度
  async getChildLearningProgress() {
    const response = await api.get('/parent/child/learning');
    return response;
  },

  // 健康检查
  async healthCheck() {
    const response = await api.get('/health');
    return response;
  },

  // 管理员接口
  async getAdminData() {
    const response = await api.get('/admin/users');
    return response;
  },

  async updateRolePermissions(data) {
    const response = await api.post('/admin/role/permissions', data);
    return response;
  },

  async updateUserRole(data) {
    const response = await api.post('/admin/user/role', data);
    return response;
  }
};

export default api;
